import json
import random
import time

import requests

from app.modules1.PublicApproach import _get_vendor_ids_from_db, get_token_result, get_last_month_range
from app.modules1.common.encryptionUtils import getResult1
from config import DB, Config


def _fetch_paginated_purchase_data():
    """分页获取采购出入库明细数据"""
    print("[DEBUG] _fetch_paginated_purchase_data() 函数开始执行")
    # 获取token
    token = get_token_result()
    print(f"[DEBUG] 获取到token: {token[:20] if token else 'None'}...")
    
    # 获取日期
    start_date, end_date = get_last_month_range()
    print(f"[DEBUG] 查询日期范围: {start_date} 到 {end_date}")
    
    # 获取月结、OEM月结供应商
    vendor_ids_str = _get_vendor_ids_from_db("月结,OEM月结")
    # vendor_ids_str = "1670362157862290432"
    print(f"[DEBUG] 获取到供应商ID: {vendor_ids_str}")
    
    url = "https://web.jackyun.com/jkyun/erp/purchorder/getpurchoutinwarehouseinfo"
    base_header = {
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "module_code": "mainframe",
        "origin": "https://web.jackyun.com",
        "referer": "https://web.jackyun.com/home/mainframe_web.html",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "Windows",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.5359.125 Safari/537.36",
        "x-requested-with": "XMLHttpRequest",
    }
    all_purchase_details = []
    page_index = 0
    page_size = 1000
    session = requests.Session()  # 使用 Session 保持连接
    # 从配置文件获取仓库ID列表（排除一件代发仓）
    warehouseIds = Config.get_warehouse_ids_string()
    print("开始获取采购出入库明细数据...")
    while True:
        header = base_header.copy()
        header["authorization"] = f"Bearer {token}"

        data_payload = {
            "getType": "1",
            "billNos": "",
            "queryDateType": "2",
            "timeType": "3",
            "startTime": start_date,
            "endTime": end_date,
            "isQuickSearch": "0",
            "inouttype": "",
            "skuIds": "",
            "brandId": "",
            "vendIds": str(vendor_ids_str),
            "cateIds": "",
            "warehouseIds": warehouseIds,
            "companyId": "1924002902255536000",  # 新疆最西域电子商务有限公司
            "settStatus": "",
            "paidStatus": "",
            "applyUserName": "",
            "busiName": "",
            "purchOfficeName": "",
            "memo": "",
            "isHideWriteOffBill": "0",
            "archived": "0",
            "pageIndex": str(page_index),
            "pageSize": str(page_size),
            "sortField": "",
            "sortOrder": "",
            "cols": '["goodsdocNo","trDate","orderDate","vendId","vendName","orderNum","goodsNo","goodsName","skuName","quantity","taxPrice","payableAmount","unitName","currencyName","abbreviation","currencyRate","vendOrderId","recDate","isCertified","noTaxPrice","noTaxAmount","taxAmount","settStatus","paidStatus","batchNo","serialNo","companyName","orderCompanyName","purchOfficeName","busiName","applyUserName","comment","rowRemark","inOutMemo","orderMemo","orderDetailRemark","warehouseName","cateName","brandName","skuBarcode","inouttype"]',
        }

        try:
            requests_data = getResult1(token, data_payload)
            response = session.post(
                url,
                headers=header,
                data=requests_data,
                timeout=(10, 30),
                proxies={"http": None, "https": None},
            )

            if response.status_code != 200:
                print(f"请求失败，状态码: {response.status_code}")
                print(f"错误响应头: {response.headers}")
                try:
                    error_detail = response.json()
                    print(
                        f"错误详情: {json.dumps(error_detail, ensure_ascii=False, indent=2)}"
                    )
                except json.JSONDecodeError:
                    print(f"错误响应内容: {response.text}")
                break  # 请求失败则停止

            print(f"正在获取第 {page_index + 1} 页数据...")
            result = response.json()
            current_page_data = result.get("result", {}).get("data", [])

            if not current_page_data:  # 如果当前页没有数据
                print("没有更多数据了")
                break

            all_purchase_details.extend(current_page_data)
            print(f"当前页获取 {len(current_page_data)} 条数据")
            print(f"累计已获取 {len(all_purchase_details)} 条数据")

            # 添加随机延迟
            delay = random.uniform(1.2, 4.0)
            print(f"等待: {delay:.1f} 秒后继续...")
            time.sleep(delay)
            page_index += 1  # 准备获取下一页

        except requests.exceptions.RequestException as e:
            print(f"请求过程中发生错误: {e}")
            break  # 网络或请求错误也停止
        except Exception as e:
            print(f"处理响应时发生未知错误: {e}")
            break  # 其他未知错误

    session.close()  # 关闭 session
    print(f"[DEBUG] 数据获取完成，总共获取 {len(all_purchase_details)} 条数据")
    # 保存数据到数据库
    print("[DEBUG] 开始调用 _save_purchase_details_to_db()")
    result = _save_purchase_details_to_db(all_purchase_details)
    print(f"[DEBUG] _save_purchase_details_to_db() 执行完成，返回值: {result}")
    return result


def _save_purchase_details_to_db(all_purchase_details):
    """将采购明细数据批量保存到数据库"""
    print(
        f"[DEBUG] _save_purchase_details_to_db() 开始执行，接收到 {len(all_purchase_details) if all_purchase_details else 0} 条数据")
    
    if not all_purchase_details:
        print("[DEBUG] 没有获取到采购明细数据，无需保存")
        print("没有获取到采购明细数据，无需保存")
        return False

    print(f"\n开始保存总计 {len(all_purchase_details)} 条数据到数据库...")
    print(f"[DEBUG] 准备连接数据库")
    
    conn = None
    cursor = None
    try:
        conn = DB()
        cursor = conn.cursor()
        print(f"[DEBUG] 数据库连接成功")

        # 先清空表中的所有数据
        truncate_sql = "TRUNCATE TABLE DZ_purchase_detail"
        cursor.execute(truncate_sql)
        print("[DEBUG] 已清空 DZ_purchase_detail 表中的所有数据")
        print("已清空 DZ_purchase_detail 表中的所有数据")

        # 直接处理所有原始数据，不进行聚合
        insert_data = []
        skipped_count = 0
        
        for item in all_purchase_details:
            vend_id = item.get("vendId")
            if vend_id is None:
                print(f"警告: 记录 {item.get('goodsdocNo')} 缺少 vendId，跳过此条记录。")
                continue

            goods_name = item.get("goodsName")
            goods_no = item.get("goodsNo")
            if (
                    "DSDF-" in goods_name
                    or "DSDF-" in goods_no
                    or goods_name.startswith("DS-")
                    or goods_no.startswith("DS-")
                    or goods_name.startswith("ds-")
                    or goods_no.startswith("ds-")
            ):
                print(f"警告: 记录 {item.get('goodsdocNo')} 包含 DSDF-或 ds，跳过此条记录。")
                skipped_count += 1
                continue

            # 直接添加每条原始记录到插入数据中
            quantity = float(item.get("quantity", 0))
            tax_price = float(item.get("taxPrice", 0))
            trans_amount = float(item.get("transHasTaxAmount", 0))

            insert_data.append((
                item.get("goodsField2"),  # purchaser
                item.get("goodsdocNo"),  # goods_doc_no
                vend_id,  # vend_id
                item.get("vendName"),  # vend_name
                item.get("orderNum"),  # order_num
                item.get("goodsNo"),  # goods_no
                goods_name,  # goods_name
                item.get("skuName"),  # sku_name
                item.get("skuId"),  # sku_id
                quantity,  # quantity
                tax_price,  # tax_price
                trans_amount,  # transHasTaxAmount
                item.get("inouttype", ""),  # in_out_type_name
                item.get("trDate")  # trDate
            ))

        if not insert_data:
            print("没有有效数据可供插入数据库。")
            return False

        # 直接插入所有原始数据
        sql = """
        INSERT INTO DZ_purchase_detail (
            purchaser,goods_doc_no, vend_id, vend_name,
            order_num, goods_no, goods_name, sku_name, sku_id,
            quantity, tax_price,transHasTaxAmount,in_out_type_name,trDate
        ) VALUES (
            %s,%s, %s, %s, %s, %s, %s, %s, %s,
            %s, %s, %s, %s, %s
        )
        """

        # 执行批量插入
        cursor.executemany(sql, insert_data)
        conn.commit()
        print(f"成功批量保存 {len(insert_data)} 条原始数据到数据库！")
        print(f"原始数据 {len(all_purchase_details)} 条，有效数据 {len(insert_data)} 条")
        if skipped_count > 0:
            print(f"已跳过 {skipped_count} 条包含'DSDF-'的商品记录")

        print(f"[DEBUG] 数据保存成功，返回 True")
        return True

    except Exception as e:
        if conn:
            conn.rollback()
        print(f"保存数据到数据库时出错: {str(e)}")
        print(f"[DEBUG] 数据保存失败，返回 False")
        return False
    finally:
        if cursor:
            cursor.close()
        if conn:
            conn.close()


# 获取月结供应商数据更新函数
def update_vendors():
    """
    更新月结供应商数据的函数。
    1. 从数据库获取月结供应商ID列表。
    2. 调用 `get_vendors_data` 函数获取月结供应商数据。
    3. 调用 `_save_vendors_to_db` 函数将月结供应商数据保存到数据库。
    """
    print("[DEBUG] update_vendors() 函数开始执行")
    try:
        result = _fetch_paginated_purchase_data()
        print(f"[DEBUG] _fetch_paginated_purchase_data() 执行完成，返回值: {result}")
        return result
    except Exception as e:
        print(f"[DEBUG] update_vendors() 执行过程中发生异常: {e}")
        raise

if __name__ == '__main__':
    update_vendors()
    # _fetch_paginated_purchase_data()
